package com.ruoyi.web.es.beans;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.elasticsearch.core.ElasticsearchRestTemplate;
import org.springframework.data.elasticsearch.core.document.Document;
import org.springframework.data.elasticsearch.core.mapping.IndexCoordinates;
import org.springframework.stereotype.Component;

import java.text.SimpleDateFormat;
import java.util.Date;

@Component
public class Bdindex {
    @Autowired
    private ElasticsearchRestTemplate restTemplate;

    synchronized public void preindex(){
        SimpleDateFormat formatter = new SimpleDateFormat("yyyyMMdd");
        //生成索引名称
        String dateString = "aqyy_log" + formatter.format(new Date());
//        String dateString = "aqyy_log20240812";
        if(ElasticSearchConfiguration.apiCallIndexNamePrefix == null){
            //服务器刚启动，初始化时
            ElasticSearchConfiguration.apiCallIndexNamePrefix = dateString;
        }

        //判断索引库中是否存在该索引
        if (!restTemplate.indexOps(IndexCoordinates.of(dateString)).exists()) {
            //时间过了，重新创建索引时
            ElasticSearchConfiguration.apiCallIndexNamePrefix = dateString;
            Document mapping = restTemplate.indexOps(IndexCoordinates.of(dateString)).createMapping(User.class);
            restTemplate.indexOps(IndexCoordinates.of(dateString)).create();
            restTemplate.indexOps(IndexCoordinates.of(dateString)).putMapping(mapping);
        }
    }
}
